package com.sqx.modules.record.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sqx.common.utils.Result;
import com.sqx.modules.record.entity.Record;
import com.sqx.modules.record.dao.RecordDao;
import com.sqx.modules.record.service.RecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author www.javacoder.top
 * @since 2023-01-18
 */
@Service
public class RecordServiceImpl extends ServiceImpl<RecordDao, Record> implements RecordService {

    @Override
    public IPage<Record> getMyRecordList(Integer page, Integer limit, Record record) {
        Page<Record> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        if(record.getUserId()==null){
            return null;
        }
        return baseMapper.selectPage(pages, new QueryWrapper<>(record).orderByDesc("create_time"));
    }

    @Override
    public Result deleteRecord(Long userId, Long recordId, Integer type) {
        if(recordId!=null){
            return Result.upStatus(baseMapper.deleteById(recordId));
        }else {
            return Result.upStatus(baseMapper.delete(new QueryWrapper<Record>().eq("user_id", userId).eq("type", type)));
        }
    }
    @Override
    public void saveRecord(Long userId, String keyWord, Integer type){
        Record hasRecord = baseMapper.selectOne(new QueryWrapper<Record>().eq("user_id", userId).eq("key_word", keyWord).eq("type", type));
        if(hasRecord!=null){
            hasRecord.setCreateTime(LocalDateTime.now());
            baseMapper.updateById(hasRecord);
        }else {
            Record record = new Record();
            record.setUserId(userId);
            record.setKeyWord(keyWord);
            record.setType(type);
            record.setCreateTime(LocalDateTime.now());
            baseMapper.insert(record);
        }
    }

    @Override
    public IPage<String> getHotKeyWord(Integer page, Integer limit) {
        Page<String> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        return baseMapper.getHotKeyWord(pages);


    }
}
